<template>
    <div class="main"  @scroll.passive="scrollTop($event)">
        <!-- 角色名称头部 -->
        <div>
            <el-space wrap :size="10">
                <span>角色名称:</span>
                <el-input v-model="name" clearable />
                <span>描述信息:</span>
                <el-input v-model="desc" clearable />
                <el-button type="primary" @click="handlerAdd" v-permission="'sys:role:create'">添加</el-button>
            </el-space>
        </div>
        <!-- 角色列表 -->
        <div>
            <el-table :data="tableData" style="width: 100%" border>
                <el-table-column prop="name" label="角色名称" align="center" />
                <el-table-column prop="desc" label="说明" align="center" />
                <el-table-column label="操作" align="center">
                    <template #default="scope">
                        <el-button type="primary" @click="handleEdit(scope.$index, scope.row)" v-permission="'sys:role:update'">修改</el-button>
                        <el-button type="primary" @click="handleAuthorization(scope.$index, scope.row)">授权</el-button>
                        <el-button type="danger" @click="handleDelete(scope.$index, scope.row)" v-permission="'sys:role:delete'">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <!-- 角色修改弹出框 -->
            <el-dialog v-model="dialogFormVisible" title="修改信息">
                <el-form :model="form">
                    <el-space wrap :size="10">
                        <el-form-item label="角色名称:">
                            <el-input v-model="form.name" autocomplete="off" />
                        </el-form-item>
                        <el-form-item label="描述信息:">
                            <el-input v-model="form.desc" autocomplete="off" />
                        </el-form-item>
                        <el-form-item>
                            <el-button type="primary" @click="etidConfirm">修改</el-button>
                        </el-form-item>
                    </el-space>
                </el-form>
            </el-dialog>
            <!-- 角色权限配置弹出框 -->
            <el-dialog v-model="centerDialogVisible" title="权限配置" width="30%" align-center>
                <el-tree :data="data" :props="defaultProps" @node-click="handleNodeClick" show-checkbox node-key="id"
                    :default-checked-keys="assignedPermissions" ref="tree">
                    <template #default="{ node, data }">
                        <span class="custom-tree-node">
                            <span>{{ node.label }}</span>
                            <span v-if="data.api">{{ data.id }}</span>
                        </span>
                    </template>
                </el-tree>
                <template #footer>
                    <span class="dialog-footer">
                        <el-button @click="centerDialogVisible = false">取消</el-button>
                        <el-button type="primary" @click="configurePermissions">确认</el-button>
                    </span>
                </template>
            </el-dialog>
        </div>
        <!-- 分页组件 -->
        <div>
            <Paging v-bind="pagingDatas" @page-change="pageChange"></Paging>
        </div>
        <el-backtop :right="100" :bottom="100" ref="main" target=".main"  :visibility-height="0"  v-if="bool"/>
    </div>
</template>
<script lang="ts" setup>
import { ref, reactive, nextTick, watch } from 'vue'
import { ClassPagination } from "#/index";
import { ElMessage, ElMessageBox } from 'element-plus'
import { post } from "@/utils/http";
import Paging from "@/components/paging/Paging.vue";
import { fromPairs } from 'lodash';
interface Tree {
    label: string
    children?: Tree[]
}
const name = ref('')//角色名称
const desc = ref('') //描述信息
//修改弹出框数据
let form = reactive({
    name: '',  //角色名称
    desc: '',  //角色描述
    status: 1,
    id: 0,
})

const dialogFormVisible = ref(false) //控制修改框是否可见
const centerDialogVisible = ref(false)
const main = ref()  //滚动组件对象的引用
const tree = ref() //获取权限列表对象引用
let bool = ref(true)//用来判断滚动组件的显示隐藏
let rollHeight = ref(0)  //滚动距离
const data = ref([]) //授权列表
let roleId = ref(0) //角色id
const assignedPermissions = ref([]) //默认选中权限
//请求分页的数据
let pagingDatas = reactive(new ClassPagination)
const tableData: TypeRoleList[] = reactive([])

const loadRoleList = () => {
    let data = {
        _gp: 'admin.role',
        _mt: 'list',
        name: '',
        page: pagingDatas.page,
        limit: pagingDatas.limit
    }
    post(data).then(res => {
        console.log(res);
        if (200 == res.errno) {
            tableData.length = 0
            tableData.push(...res.data.items)
            pagingDatas.total = res.data.total
        } else {
            ElMessage.error(res.errmsg)
            pagingDatas.total = 0
        }

    })
}
loadRoleList()

//修改
const handleEdit = (index: number, row: TypeRoleList) => {
    console.log(index, row)
    dialogFormVisible.value = true
    Object.assign(form, row)
}
//修改确认
const etidConfirm = () => {
    let data = {
        _gp: 'admin.role',
        _mt: 'update',
        role: JSON.stringify({ 'name': form.name, 'desc': form.desc, 'status': form.status, 'id': form.id })
    }
   if(form.name!=''){
    post(data).then(res => {
        if (200 == res.errno) {
            ElMessage.success('修改成功')
            dialogFormVisible.value = false
            loadRoleList()
        } else {
            ElMessage.error(res.errmsg)
        }
    })
   }else{
     ElMessage.error("角色名称不能为空")
   }
}
//添加
const handlerAdd = () => {
    if (name.value!='') {
        let data = {
            _gp: 'admin.role',
            _mt: 'create',
            role: JSON.stringify({ 'name': name.value, 'desc': desc.value, 'status': 1 })
        }
        post(data).then(res => {
            console.log(res);
            if (200 == res.errno) {
                ElMessage.success('添加成功')
                name.value = ''
                desc.value = ''
                loadRoleList()
            } else {
                ElMessage.error(res.errmsg)
            }
        })
    } else {
        ElMessage.error('角色名称不能为空')
    }
}
const defaultProps = {
    children: 'children',
    label: 'label',
}

//授权列表
const handleAuthorization = (index: number, row: TypeRoleList) => {
    roleId.value = row.id //获取角色id
    assignedPermissions.value = []  //每次点击给它清空默认选中权限
    let datas = {
        _gp: 'admin.role',
        _mt: 'permissionList',
        roleId: row.id
    }
    post(datas).then(res => {
        console.log(res);
        if (200 == res.errno) {
            data.value = res.data.systemPermissions
            assignedPermissions.value = res.data.assignedPermissions
            nextTick(() => {
                centerDialogVisible.value = true
            })
        }else{
            ElMessage.error(res.errmsg)
        }
    })
}
//配置权限
const configurePermissions = () => {
     let getdata = tree.value.getCheckedKeys(true)  //获取当前选中的权限
     let data = {
        _gp:'admin.role',
        _mt:"permissionSet",
        roleSetPermissionDTO:JSON.stringify({'roleId':roleId.value,'permissions':getdata})
     }
    post(data).then(res=>{
        console.log(res)
        if(200==res.errno){
            centerDialogVisible.value = false
            ElMessage.success('授权成功')
        }else{
            ElMessage.success(res.errmsg)
        }
    })
}
const handleNodeClick = (data: Tree) => {
    console.log(data)
}



//删除
const handleDelete = (index: number, row: TypeRoleList) => {
    console.log(index, row)
    let data = {
        _gp: "admin.role",
        _mt: 'delete',
        roleId: row.id
    }
    ElMessageBox.confirm(
        '请问是否删除',
        '消息提示',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
        }
    )
        .then(() => {
            post(data).then(res => {
                if (200 == res.errno) {
                    ElMessage.success('删除成功')
                    loadRoleList()
                } else {
                    ElMessage.error(res.errmsg)
                }
            })

        })
        .catch(() => {
            ElMessage.info('取消操作')
        })
}

//分页组件每次调用事件
function pageChange(e: TypePaGing) {
    pagingDatas.page = e._page
    pagingDatas.limit = e._limit
    loadRoleList()
    nextTick(() => {
        main.value.$el.click?.()
    })
}
//滚动事件
let scrollTop=(e:Event)=>{
    rollHeight.value=Math.floor((e.target as EventTarget).scrollTop)
}
//监听滚动的距离
watch(rollHeight,(val:number)=>{
//    console.log(val);
  bool.value = val>60
})

</script>
<style lang="less" scoped>
.main {
    >div:nth-child(1) {
        margin: 15px 0px;

        .el-input {
            width: 15vw;
        }
    }

    .dialog-footer button:first-child {
        margin-right: 10px;
    }

    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
}
</style>